var express = require("express");
var router = express.Router();
var multiparty = require("multiparty");
var { userModel, 
  role,
   menu, 
   ordermanagement, 
   listModel,
  stag,
  cateModel, 
  Coupon, 
  pcuser,
  order } = require("../model/model.js");
var jwt = require("jsonwebtoken");
var Svgcatcha = require("svg-captcha");

const bodyParser = require("body-parser");
const fse = require("fs-extra");
const path = require("path");
const multipart = require("connect-multiparty");
const multipartMiddleware = multipart();
const UPLOADS_DIR = path.resolve("uploads");



// 商品分类

router.get("/cate1", async (req, res) => {
  let data = await cateModel.find()
  res.send({
    code: 200,
    data,
  });
});

router.get("/catels", async (req, res) => {
  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (title) que.push({ title: title })
  if (que.length == 0) {
    data = await cateModel.find().populate('fid').skip((page - 1) * pagesize).limit(pagesize)
    num = await cateModel.countDocuments()
  } else {
    data = await cateModel.find({ $and: que }).populate('fid').skip((page - 1) * pagesize).limit(pagesize)
    num = (await cateModel.find({ $and: que })).length
  }
  let data1 = await cateModel.find().populate('fid')

  res.send({
    code: 200,
    data, num, data1
  });
});

router.post("/cateadd", async (req, res) => {


  await cateModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

router.post('/cateupdate', async (req, res) => {
  await cateModel.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/catedel', async (req, res) => {
  await cateModel.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})

//商品标签

router.get("/stag1", async (req, res) => {

  let data = await stag.find()
  res.send({
    code: 200,
    data,
  });
});

router.get("/stag", async (req, res) => {
  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (title) que.push({ name: title })
  if (que.length == 0) {
    data = await stag.find().skip((page - 1) * pagesize).limit(pagesize)
    num = await stag.countDocuments()
  } else {
    data = await stag.find({ $and: que }).skip((page - 1) * pagesize).limit(pagesize)
    num = (await stag.find({ $and: que })).length
  }
  let data1 = await stag.find()

  res.send({
    code: 200,
    data, num, data1
  });
});

router.post("/stagadd", async (req, res) => {
  await stag.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

router.post('/stagupdate', async (req, res) => {
  await stag.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/stagedel', async (req, res) => {
  await stag.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})

//商品
// 回显商品
router.get("/list1", async (req, res) => {
  let data = []
  if (req.query.id) {
    data = await listModel.find({ _id: req.query.id }).populate('stag').populate('cid')
  } else {
    data = await listModel.find().populate('stag').populate('cid')
  }
  res.send({
    code: 200,
    data,
  });
});
// 查看所有商品
router.get("/list2", async (req, res) => {
  let data  = await listModel.find().populate('stag').populate('cid')
  res.send({
    code: 200,
    list:data,
  });
});

router.get("/list", async (req, res) => {
  let { page, pagesize, name, cid, stag1, da, xiao } = req.query
  console.log(req.query);

  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)

  if (title) que.push({ name: title })
  if (stag1) que.push({ stag: stag })
  if (cid) que.push({ cid: cid })
  if (da) que.push({ num: { $lte: da } })
  if (xiao) que.push({ num: { $gte: xiao } })
  console.log(que);

  if (que.length == 0) {
    data = await listModel.find().populate('stag').populate('cid').populate('fid').skip((page - 1) * pagesize).limit(pagesize)
    num = await listModel.countDocuments()
  } else {
    data = await listModel.find({ $and: que }).populate('stag').populate('cid').skip((page - 1) * pagesize).limit(pagesize)
    num = (await listModel.find({ $and: que })).length
  }
  let data1 = await stag.find()

  res.send({
    code: 200,
    data, num, data1
  });
});
router.post("/listadd", (req, res) => {
  listModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});

router.post('/listupdate', async (req, res) => {
  await listModel.updateOne({ _id: req.query.id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/listdel', async (req, res) => {
  await listModel.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})

// 小文件上传
router.post('/upload', async (req, res) => {
  let form = new multiparty.Form()
  form.uploadDir = 'uploads'
  form.parse(req, (a, b, img) => {
    console.log(img);
    let path = 'http://localhost:3000/' + img.file[0].path
    res.send({
      path
    })
  })
})
// 大文件上传
router.post("/upload1", multipartMiddleware, (req, res) => {
  const { fileHash, chunkHash } = req.body;

  // 如果临时文件夹(用于保存分片)不存在，则创建
  const chunkDir = path.resolve(UPLOADS_DIR, fileHash);
  if (!fse.existsSync(chunkDir)) {
    fse.mkdirSync(chunkDir);
  }

  // 如果临时文件夹里不存在该分片，则将用户上传的分片移到临时文件夹里
  const chunkPath = path.resolve(chunkDir, chunkHash);
  if (!fse.existsSync(chunkPath)) {
    fse.moveSync(req.files.chunk.path, chunkPath);
  }

  res.send({
    success: true,
    msg: "上传成功",
  });
});

/**
 * 合并
 */
router.post("/merge", async (req, res) => {
  const { fileHash, fileName } = req.body;

  // 最终合并的文件路径
  const filePath = path.resolve(UPLOADS_DIR, fileHash + path.extname(fileName));
  // 临时文件夹路径
  const chunkDir = path.resolve(UPLOADS_DIR, fileHash);

  // 读取临时文件夹，获取该文件夹下“所有文件（分片）名称”的数组对象
  const chunkPaths = fse.readdirSync(chunkDir);

  // 读取临时文件夹获得的文件（分片）名称数组可能乱序，需要重新排序
  chunkPaths.sort((a, b) => a.split("-")[1] - b.split("-")[1]);

  // 遍历文件（分片）数组，将分片追加到文件中
  const pool = chunkPaths.map(
    (chunkName) =>
      new Promise((resolve) => {
        const chunkPath = path.resolve(chunkDir, chunkName);
        // 将分片追加到文件中
        fse.appendFileSync(filePath, fse.readFileSync(chunkPath));
        // 删除分片
        // fse.unlinkSync(chunkPath);
        resolve();
      })
  );
  await Promise.all(pool);
  // 等待所有分片追加到文件后，删除临时文件夹
  fse.removeSync(chunkDir);

  res.send({
    success: true,
    msg: "合并成功",
  });
});

/**
 * 校验
 */
router.post("/verify", (req, res) => {
  const { fileHash, fileName } = req.body;
  console.log(req.body);

  // 判断服务器上是否存在该hash值的文件
  const filePath = path.resolve(UPLOADS_DIR, fileHash + path.extname(fileName));
  const existFile = fse.existsSync(filePath);

  // 获取已经上传到服务器的文件分片
  const chunkDir = path.resolve(UPLOADS_DIR, fileHash);
  const existChunks = [];
  if (fse.existsSync(chunkDir)) {
    existChunks.push(...fse.readdirSync(chunkDir));
  }

  res.send({
    success: true,
    msg: "校验文件",
    data: {
      existFile,
      existChunks,
    },
  });
});



// 角色


router.get('/role1', async (req, res) => {

  let data =await role.find()
 

  res.send({
    code: 200,
    data
  });
})

router.get('/role', async (req, res) => {

  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (title != '') que.push({ name: title })
  if (que.length == 0) {
    data = await role.find().skip((page - 1) * pagesize).limit(pagesize)
    console.log(data);

    num = await role.countDocuments()
  } else {
    data = await role.find({ $and: que }).skip((page - 1) * pagesize).limit(pagesize)
    num = (await role.find({ $and: que })).length
  }
  let data1 = await role.find()
  console.log(que);

  res.send({
    code: 200,
    data, num, data1
  });
})

router.post('/roleadd', async (req, res) => {
  await role.create(req.body)
  res.send({
    code: 200
  })
})

router.post('/roleupdate', async (req, res) => {
  await role.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/roledel', async (req, res) => {
  await role.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})


// 菜单
router.get('/menu', async (req, res) => {
  let { role_id } = req.body;

  let menus = await menu.find();

  let menuList = await menu.find().lean();

  // console.log(menuList);
  let menuArr = []
  menus.forEach(item => {
    menuList.forEach(item1 => {
      if (String(item._id) == String(item1._id)) {
        item1['value'] = item1._id
        item1['label'] = item1.name
        menuArr.push(item1)
      }
    })
  })
  // console.log(menuArr);
  let menuObj = {}
  menuArr.forEach(item => {
    menuObj[item._id] = item
  })
  // console.log(menuObj);
  let arr = []
  menuArr.forEach(item => {
    if (!item.parentId) {
      arr.push(item)
    } else {
      if (menuObj[item.parentId] && !menuObj[item.parentId].children) {
        menuObj[item.parentId].children = []
      }
      menuObj[item.parentId] && menuObj[item.parentId].children.push(item)
    }
  })
  console.log(arr);

  res.send({
    code: 200,
    msg: "获取成功",
    arr
  });
})



// 优惠卷
router.get('/coupon', async (req, res) => {

  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (title) que.push({ name: name })
  if (que.length == 0) {
    data = await Coupon.find().skip((page - 1) * pagesize).limit(pagesize)
    console.log(data);

    num = await Coupon.countDocuments()
  } else {
    data = await Coupon.find({ $and: que }).skip((page - 1) * pagesize).limit(pagesize)
    num = (await Coupon.find({ $and: que })).length
  }
  let data1 = await Coupon.find()
  console.log(que);

  res.send({
    code: 200,
    data, num, data1
  });
})

router.post('/couponadd', async (req, res) => {
  await Coupon.create(req.body)
  res.send({
    code: 200
  })
})

router.post('/couponupdate', async (req, res) => {
  await Coupon.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/coupondel', async (req, res) => {
  await Coupon.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})


// pc端账号
router.get('/pcuser', async (req, res) => {

  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (title) que.push({ name: name })
  if (que.length == 0) {
    data = await pcuser.find().skip((page - 1) * pagesize).limit(pagesize)
    console.log(data);

    num = await pcuser.countDocuments()
  } else {
    data = await pcuser.find({ $and: que }).skip((page - 1) * pagesize).limit(pagesize)
    num = (await pcuser.find({ $and: que })).length
  }
  let data1 = await pcuser.find()
  console.log(que);

  res.send({
    code: 200,
    data, num, data1
  });
})

router.post('/pcuseradd', async (req, res) => {
  await pcuser.create(req.body)
  res.send({
    code: 200
  })
})

router.post('/pcuseradd', async (req, res) => {
  await pcuser.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/pcuseradd', async (req, res) => {
  await pcuser.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})

// 移动用户表

router.get('/user1', async (req, res) => {
  let data1 = await userModel.find()

  res.send({
    code: 200,
    list:data1
  });
})

router.get('/user', async (req, res) => {

  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (title) que.push({ name: name })
  if (que.length == 0) {
    data = await userModel.find().skip((page - 1) * pagesize).limit(pagesize)
    console.log(data);

    num = await userModel.countDocuments()
  } else {
    data = await userModel.find({ $and: que }).skip((page - 1) * pagesize).limit(pagesize)
    num = (await userModel.find({ $and: que })).length
  }
  let data1 = await userModel.find()
  console.log(que);

  res.send({
    code: 200,
    data, num, data1
  });
})

router.post('/useradd', async (req, res) => {
  await userModel.create(req.body)
  res.send({
    code: 200
  })
})

router.post('/userupdate', async (req, res) => {
  await userModel.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/userdel', async (req, res) => {
  await userModel.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})

//订单表
router.get('/order', async (req, res) => {

  let { page, pagesize, name } = req.query
  let data = []
  let que = []
  let num = 0
  let title = new RegExp(name)
  if (name) que.push({ address: title })
  if (que.length == 0) {
    data = await order.find().populate('shopid').populate('uid').skip((page - 1) * pagesize).limit(pagesize)
    console.log(data);

    num = await order.countDocuments()
  } else {
    data = await order.find({ $and: que }).populate('shopid').skip((page - 1) * pagesize).limit(pagesize)
    num = (await order.find({ $and: que })).length
  }
  let data1 = await order.find()
  console.log(que);

  res.send({
    code: 200,
    data, num, data1
  });
})

router.post('/orderadd', async (req, res) => {
  await order.create(req.body)
  res.send({
    code: 200
  })
})

router.post('/orderupdate', async (req, res) => {
  await order.updateOne({ _id: req.body._id }, req.body)
  res.send({
    code: 200
  })
})

router.post('/orderdel', async (req, res) => {
  await order.deleteOne({ _id: req.body._id })
  res.send({
    code: 200
  })
})


module.exports = router;